//
//  DHMineController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/7.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHMineViewController.h"
#import "DHHeaderCell.h"
#import "DHFunctionCell.h"
#import "DHSafeAccountControntroller.h"
#import "DHBillController.h"
#import "JPPostTaskController.h"
#import "DHMainController.h"
NSString *headerViewID = @"headerViewID";
NSString *functionCellID = @"functionCellID";
@interface DHMineViewController ()<UITableViewDelegate, UITableViewDataSource,
                                    DHFunctionDelegate,DHHeaderCellDelegate,
                                UIActionSheetDelegate, UIImagePickerControllerDelegate,
                                        UINavigationControllerDelegate>
@property(nonatomic ,strong)DHMemberInfoModel *model;
@property(nonatomic ,strong)NSMutableArray *normalCellInfo;
@property(nonatomic ,strong)UITableView *mineTableView;

@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController

@end

@implementation DHMineViewController

- (UITableView *)mineTableView{
    if (!_mineTableView) {
        _mineTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    }
    return _mineTableView;
}
// 重写父类方法
- (void)shouldLogWeb
{
    
}
#pragma mark: - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    
    
    DHBaseController *vc = viewController.childViewControllers.firstObject;
    
    if ([vc isMemberOfClass:[DHServiceController class]]) {
        // 判断手机是否安装QQ
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",DHNetworkManager.shareManager.qq]];
        if([[UIApplication sharedApplication] canOpenURL:url]){
            [[UIApplication sharedApplication] openURL:url];
            
        } else {
            UIAlertView*ale=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有安装手机QQ，请安装手机QQ后重试，或用PC进行操作。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            ale.delegate = self;
            [ale show];
            
        }
        return NO;
    }
    // NSLog(@"%@---%@",viewController.childViewControllers.firstObject,[self class]);
    
    return YES;
    
    // NSLog(@"%@---%@",viewController.childViewControllers.firstObject,[self class]);
    
    
}
- (NSMutableArray *)normalCellInfo{
    if (!_normalCellInfo) {
        NSArray *array = @[@[@{@"cellName":@"我的清洁订单",@"imgName":@"1",@"clsName":@"DHCleanOrderController"},
                             @{@"cellName":@"服务管理规则",@"imgName":@"2",@"clsName":@"DHWebViewController",@"url":@"http://jpjd.cnaite.cn/wap/index.php?act=index&op=getServerRule"},
                            @{@"cellName":@"账户明细",@"imgName":@"3",@"clsName":@"DHBillController"},
                            @{@"cellName":@"账户信息",@"imgName":@"4",@"clsName":@"DHUserInfoController"},
                            @{@"cellName":@"商户入驻",@"imgName":@"商户入驻",@"clsName":@"DHCommerController"},
                            @{@"cellName":@"账户安全",@"imgName":@"账户安全",@"clsName":@"DHSafeAccountControntroller"},
                            @{@"cellName":@"在线充值",@"imgName":@"在线充值",@"clsName":@"MutiChargeViewController"},
                            @{@"cellName":@"消息中心",@"imgName":@"5",@"clsName":@"BCHeadLetterTableViewController"},
                            @{@"cellName":@"去商城",@"imgName":@"2",@"clsName":@"DHWebViewController",@"url":@"http://jpjd.cnaite.cn/wap"},
                            @{@"cellName":@"退出登录",@"imgName":@"6",@"clsName":@"logout"}],
                           
                            @[@{@"cellName":@"我发布的任务",@"imgName":@"2",@"clsName":@"DHPostTaskController"},
                            @{@"cellName":@"发布任务",@"imgName":@"6",@"clsName":@"JPPostTaskController"}]
                           ];
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSArray *list in array)
        {
            [arrayM addObject:[NSArray yy_modelArrayWithClass:[DHNorCellInfo class] json:list]];
        }
        _normalCellInfo = arrayM.copy;
    }
    return _normalCellInfo;
}

- (void)setModel:(DHMemberInfoModel *)model{
    _model = model;
    
 
    [self.mineTableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (DHNetworkManager.shareManager.userAccount.is_store.boolValue) {
        [self.normalCellInfo.firstObject removeObjectAtIndex:4];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;

}
- (void)setupTableView{
    self.navigationController.navigationBar.hidden = true;
    
    [self loadData];
    self.mineTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.mineTableView.contentInset = UIEdgeInsetsMake(-56, 0, 0, 0);
    self.mineTableView.delegate = self;
    self.mineTableView.dataSource = self;
    [self.view addSubview:self.mineTableView];
    
    [self.mineTableView registerNib:[UINib nibWithNibName:@"DHHeaderCell" bundle:nil] forCellReuseIdentifier:headerViewID];
    [self.mineTableView registerNib:[UINib nibWithNibName:@"DHFunctionCell" bundle:nil] forCellReuseIdentifier:functionCellID];
    //self.tableView.bounces = false;
    
    self.mineTableView.backgroundColor = [UIColor colorWithRed:245.0f/255.0f green:245.0f/255.0f blue:248.0f/255.0f alpha:1];
    
    //判断是否申请商户认证了
    }
#pragma mark: - 加载数据
- (void)loadData
{
    [DHNetworkManager.shareManager
     requestMineInfoWithKey:DHNetworkManager.shareManager.userAccount.key
    completion:^(DHMemberInfoModel *model, BOOL isSuccess)
     {
         if (!isSuccess) {
             [SVProgressHUD showErrorWithStatus:@"请检查网络"];
             return ;
         }
         self.model = model;
     }];
}

#pragma mark: - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    NSInteger numSection = DHNetworkManager.shareManager.userAccount.is_store.boolValue ? self.normalCellInfo.count : 1;
  
    return numSection;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ? [self.normalCellInfo[section] count] + 1 : [self.normalCellInfo[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getCellIdWithIdxPathRow:indexPath]forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self setupCell:cell idx:indexPath];
    cell.tag = indexPath.row;
    return cell;
}

#pragma mark: - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGFloat rowHeight = (indexPath.section == 0) ? ((indexPath.row == 0) ? 250 : 44) : 44;
    return rowHeight;
}

#pragma mark: - cell点击事件监听
- (void)functionCell:(DHFunctionCell *)cell didClickCellWithInfo:(DHNorCellInfo *)info
{
   
    [self pushToController:info];
}
#pragma mark: - 跳转控制器
- (void)pushToController:(DHNorCellInfo *)info
{
    if ([info.clsName isEqualToString:@"logout"]) {

        DHNetworkManager.shareManager.userAccount.lastUserID = DHNetworkManager.shareManager.userAccount.userid;
        DHNetworkManager.shareManager.userAccount.username = nil;
        DHNetworkManager.shareManager.userAccount.key = nil;
        DHNetworkManager.shareManager.userAccount.is_auth = nil;
        DHNetworkManager.shareManager.userAccount.is_store = nil;
        DHNetworkManager.shareManager.userAccount.userid = nil;
        DHNetworkManager.shareManager.userAccount.islogout = false;
        DHNetworkManager.shareManager.userAccount.access_token = false;
        DHNetworkManager.shareManager.userAccount.access_token_exptime = nil;
        
        [DHNetworkManager.shareManager.userAccount saveAccount];
        DHMainController *mVc = [DHMainController new];
        [UIApplication.sharedApplication keyWindow].rootViewController = mVc;
  
        return;
        
    }
    UIViewController *vc;
    if ([info.clsName isEqualToString:@"DHCommerController"])
    {
        vc = [DHCommerController commerContronller];
    }else if([info.clsName isEqualToString:@"DHUserInfoController"])
    {
        vc = [DHUserInfoController userInfo];
    }else if([info.clsName isEqualToString:@"DHSafeAccountControntroller"]){
        vc = [DHSafeAccountControntroller safeContronller];
    }else if([info.clsName isEqualToString:@"JPPostTaskController"]){
        
        vc = [JPPostTaskController postTaskVC];
        
    }else{
        vc = [[NSClassFromString(info.clsName) alloc] init];

    }
    
    // 去商城
    if ([vc isMemberOfClass:[DHWebViewController class]])
    {
        [(DHWebViewController *)vc setUrlStr:info.url];
        vc.navigationController.navigationBar.hidden = false;
    }
    // 我的订单
    if ([vc isMemberOfClass:[DHCleanOrderController class]])
    {

    }
  
    vc.hidesBottomBarWhenPushed = true;
    [self.navigationController pushViewController:vc animated:true];
}


#pragma mark: - 设置cell数据
- (void)setupCell:(UITableViewCell *)cell idx:(NSIndexPath *)idx{
    
    switch (idx.section)
    {
        case 0:
            switch (idx.row)
            {
                case 0:
                    [(DHHeaderCell *)cell setModel:self.model];
                    [(DHHeaderCell *)cell setDelegate:self];
                    break;
                    
                default:
                    [(DHFunctionCell *)cell setCellInfo:self.normalCellInfo[idx.section][idx.row - 1]];
                    [(DHFunctionCell *)cell setDelegate:self];
        
                    break;
            }
            break;
            
        default:
            [(DHFunctionCell *)cell setCellInfo:self.normalCellInfo[idx.section][idx.row]];
            [(DHFunctionCell *)cell setDelegate:self];
            break;
    }
    
}
#pragma mark: - DHHeaderCellDelegate
- (void)headerCell:(DHHeaderCell *)cell selectedMothlyButtonTag:(NSInteger)tag
{
    UIViewController *vc;
    switch (tag) {
        case 0: // 本月清洁单
            vc = [[DHCleanOrderController alloc] init];
            [(DHCleanOrderController *)vc setIs_mouth:@"1"];
            break;
        case 1:  // 本月收入
            vc = [[DHBillController alloc] init];
            [(DHBillController *)vc setIs_mouth:YES];
            break;
        case 2: // 用户评价
            vc = [[DHEvaluateController alloc] init];
            [(DHEvaluateController *)vc setType:@"0"];
            break;
        }
    vc.hidesBottomBarWhenPushed = true;
    [self.navigationController pushViewController:vc animated:true];
}
- (void)headerCellChangeIcon:(DHHeaderCell *)cell
{
    //自定义消息框
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 2550;
    //显示消息框
    [sheet showInView:self.view];
}
#pragma mark -消息框代理实现-
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 2550) {
        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType; //图片来源
            if (buttonIndex == 0) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
                
            }else if (buttonIndex == 1) {
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
            }else if (buttonIndex == 2){
                
                return;
            }
        }else {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
}
#pragma mark -实现图片选择器代理-（上传图片的网络请求也是在这个方法里面进行，这里我不再介绍具体怎么上传图片）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
    
    [self postUserImageFormDateWithIcon:image];
}

- (void)postUserImageFormDateWithIcon:(UIImage *)icon{
    
    //    NSString * sexString =[self.sexSelectButton.titleLabel.text isEqualToString:@"男"]?@"1":@"0";
    //
    //    NSDictionary *dict = @{@"key":[UserManager shareUser].key, @"mobile":self.phoneTextField.text,@"level_id":self.VIP_id,@"level_name":self.rankTextField.text,@"tuijian_member_name":self.recommenTextField.text,@"auth_name":self.realNameTextField.text,@"auth_card":self.idCarTextField.text,@"auth_sex":sexString};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/plain", nil];
    //图像
    NSData *imgData1 = nil;
    imgData1 =UIImageJPEGRepresentation(icon,1);
    if ([imgData1 length]/1024<=100) {
        imgData1 =UIImageJPEGRepresentation(icon,1);
        
    }else{
        
        imgData1 =UIImageJPEGRepresentation([self compressImage:icon toByte:100*1024],0.5);
    }
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    dictM[@"key"] = DHNetworkManager.shareManager.userAccount.key;
//    NSArray *nameArray = @[@"id_card_img",@"auth_fm_imgurl",@"auth_sc_imgurl"];
    NSString *name = @"avatar";
    [manager POST:@"http://jpjd.cnaite.cn/mobile/index.php?act=member_index&op=changeAvatar"
       parameters:dictM.copy constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
           
           
           
           [formData appendPartWithFileData:imgData1
                                       name:name
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
           
           
           
       } progress:nil
          success:^(NSURLSessionTask *task, id responseObject) {
              
              //  NSString * errorStr;
              id temp = responseObject[@"datas"];
              
              if (temp[@"succ"]) {
                  //                  [XHToast showBottomWithText:@"提交成功" duration:2];
                  //                  [self checkTheApplyStatus];
                  [SVProgressHUD showSuccessWithStatus:temp[@"succ"]];
                  self.model = nil;
                  [self loadData];
                  [self.mineTableView reloadData];

              }
              
              
          }
     
          failure:^(NSURLSessionTask *task, NSError *error) {
              NSLog(@"error:%@", error);
              
              
              
          }];
    
    
}
#pragma mark: - 压缩图像
- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    
    
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    UIImage *resultImage = [UIImage imageWithData:data];
    
    if (data.length < maxLength)
        
        return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        
    }
    
    return resultImage;
}
#pragma mark -- 上传头像Data
- (NSString*)returnFielName{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    return fileName;
}
#pragma mark: - getCellid
- (NSString *)getCellIdWithIdxPathRow:(NSIndexPath *)idxPath
{
    if (idxPath.section == 0 && idxPath.row == 0) {
        return headerViewID;
    }
    return functionCellID;
}



@end
